<template>
  <div>
    <el-button @click="connectAndRead">Test Connect Gateway</el-button>
    <div id="output">{{ output }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";

const output = ref<string>("");

const connectAndRead = async () => {
  if (!(navigator as any).bluetooth) {
    ElMessage.error("Web Bluetooth API not support");
    return;
  }

  try {
    const device = await (navigator as any).bluetooth.requestDevice({
      acceptAllDevices: true,
    });

    const server = await device.gatt.connect();
    output.value = `connected: ${device.name}`;
    alert(`connected ${device.name}`);

    const wifiService = await server.getPrimaryService(0xa00a);
    const batteryChar = await wifiService.getCharacteristic(0xd007);
    const batteryValue = await batteryChar.readValue();
    const decoder = new TextDecoder("utf-8");
    const stringValue = decoder.decode(batteryValue.buffer);
    const wifis = stringValue.split(",");

    console.log(`Result：${wifis[0]}`);

    const wifiWriteChar = await wifiService.getCharacteristic(0xd002);
    await wifiWriteChar.writeValue(new TextEncoder().encode(`ID=${wifis[0]}`));

    const wifiReadChar = await wifiService.getCharacteristic(0xd001);
    const wifiReadNow = await wifiReadChar.readValue();
    const nowSSID = decoder.decode(wifiReadNow.buffer);
    console.log(`Now SSID :${nowSSID}`);

    const wifiWritePasswdChar = await wifiService.getCharacteristic(0xd005);
    await wifiWritePasswdChar.writeValue(new TextEncoder().encode(`PW=28905837`));

    const wifiPwReadChar = await wifiService.getCharacteristic(0xd006);
    const wifiPwNow = await wifiPwReadChar.readValue();
    const nowSSIDPw = decoder.decode(wifiPwNow.buffer);
    console.log(`NOW PW: ${nowSSIDPw}`);
  } catch (error) {
    console.error("connect faild:", error);
  }
};
</script>

<style>
#output {
  margin-top: 20px;
}
</style>
